package com.example.controller;

import com.alibaba.csp.sentinel.annotation.SentinelResource;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.entity.PageVO;
import com.example.entity.Product;
import com.example.service.ProductService;
import jakarta.annotation.Resource;

import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
public class ProductController {

    @Resource
    private ProductService productService;

    @SentinelResource(value = "product/{id}", blockHandler = "findProductByIdBlockHandler",
            blockHandlerClass = MyBlockHandler.class)
    @RequestMapping("/product/{id}")
    public ResponseEntity<Product> findProductById(@PathVariable Integer id) {
        Product product = productService.getById(id);
        return ResponseEntity.ok(product);
    }


    @GetMapping("/products")
    public ResponseEntity<List<Product>> findAllProducts() {
        List<Product> List = productService.list();
        return ResponseEntity.ok(List);
    }

    @GetMapping("/product-page")
    public ResponseEntity<PageVO> findProductPage(
            @RequestParam(value="current",required = false,defaultValue = "1") Integer current,
            @RequestParam(value="pagesize",required = false,defaultValue = "10") Integer pagesize){
        Page<Product> page =productService.page(new Page<>(current,pagesize));
        PageVO pageVO = new PageVO(current, page.getRecords(), pagesize, page.getTotal());
        return ResponseEntity.ok(pageVO);
    }

    @PostMapping("/product")
    public ResponseEntity <String> addProduct(@RequestBody Product product) {
        productService.save(product);
        return ResponseEntity.ok("success");
    }

    @PutMapping("/product")
    public ResponseEntity <String> updateProduct(@RequestBody Product product) {
        productService.updateById(product);
        return ResponseEntity.ok("success");
    }

    @DeleteMapping("/product/{id}")
    public ResponseEntity <String> deleteProduct(@PathVariable Integer id) {
        productService.removeById(id);
        return ResponseEntity.ok("success");
    }


}
